package com.truongnha.clienttn.data.sao;

import org.json.JSONArray;
import org.json.JSONObject;

import com.truongnha.clienttn.data.dao.AccountDAO;
import com.truongnha.clienttn.data.dao.CreateDatabase;
import com.truongnha.clienttn.data.dao.StudentMarkDAO;
import com.truongnha.clienttn.data.dao.StudentSubjectDAO;
import com.truongnha.clienttn.data.entity.AccountEntity;
import com.truongnha.clienttn.data.servicehelper.utils;

import config.Url;

import android.content.Context;
import android.util.Log;

public class StudentMarkSAO {
	private Context context;
	private String url;

	public StudentMarkSAO(Context context) {
		super();
		this.context = context;

		CreateDatabase db = new CreateDatabase(context);
		AccountDAO accountDAO = new AccountDAO(db.open());
		AccountEntity accountEntity = accountDAO.getCurrentAccount();

		this.url = Url.getURLGetMarkForStudent()
				+ accountEntity.getPositionId();

	}

	private void saveToDatabase(JSONArray jsArray) {

		CreateDatabase db = new CreateDatabase(context);
		StudentMarkDAO studentMarkDAO = new StudentMarkDAO(db.open());
		studentMarkDAO.delete();
		StudentSubjectDAO studentSubjectDAO = new StudentSubjectDAO(
				db.getDatabase());
		studentSubjectDAO.delete();
		try {
			int size = jsArray.length();
			for (int i = 0; i < size; i++) {
				JSONObject js = jsArray.getJSONObject(i);
				studentSubjectDAO.insert(js.getInt("id"), js.getString("name"));
				JSONArray markArray = js.getJSONArray("mark");

				int sizeOfMarkArray = markArray.length();
				for (int j = 0; j < sizeOfMarkArray; j++) {
					JSONObject aMark = markArray.getJSONObject(j);
					studentMarkDAO.insert(js.getInt("id"), aMark.getInt("n"),
							aMark.getString("m"), aMark.getString("t"));
				}
			}
			db.close();
		} catch (Exception e) {
			db.close();
			Log.d("LOG error", " error in save attend " + e.toString());
		}
	}

	public void getMarkFromServer() {
		JSONArray jsArray = utils.getJSONArrayByHttpGet(url);
		saveToDatabase(jsArray);
	}
}
